package com.sunshine.model;

import com.sunshine.bean.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * Created by along on 4/19/18.
 */
@Mapper
public interface UserMapper {

    @Select("SELECT * FROM users WHERE id = #{id} LIMIT 1")
    @Results(id = "UserMap", value = {
            @Result(property = "id", column = "id"),
            @Result(property = "name", column = "name"),
            @Result(property = "password", column = "password"),
            @Result(property = "nickname", column = "nickname"),
            @Result(property = "role", column = "role"),
            @Result(property = "createdAt", column = "created_at")
    })
    User findById(@Param("id") int id);

    @Select("SELECT * FROM users")
    @ResultMap("UserMap")
    List<User> findAll();

    @Insert("INSERT INTO users(name, password, nickname, role, created_at) "
            + " VALUES(#{name}, #{password}, #{nickname}, #{role}, now())")
    @SelectKey(statement = "select  LAST_INSERT_ID() as id", keyProperty = "id", before = false, resultType = int.class)
    int insert(User user);

    @Select("SELECT * FROM users WHERE name = #{name} LIMIT 1")
    @ResultMap("UserMap")
    User findByName(@Param("name") String name);

    @Update("UPDATE users SET password = #{password}, nickname = #{nickname}, role = #{role} WHERE id = #{id}")
    int update(User user);

    /**
     * WARN: Just for test
     *
     * @return Deleted count
     */
    @Delete("DELETE FROM users")
    int clear();
}
